package xx.listener;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import xx.services.util.Online;

public class SessionListener extends HttpServlet implements HttpSessionListener,
        HttpSessionAttributeListener, HttpSessionBindingListener
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private static int sessionCounter = 0;

    private static int attributeCounter = 0;

    public void sessionCreated(HttpSessionEvent event)
    {
        sessionCounter++;
        Online.created(event.getSession());
        System.out.println("session created");
    }

    public void sessionDestroyed(HttpSessionEvent event)
    {
        sessionCounter--;
        Online.destroyed(event.getSession().getId());
        System.out.println("session destroied");
    }

    public void attributeAdded(HttpSessionBindingEvent event)
    {
        attributeCounter++;
        System.out.println("attribute added");
    }

    public void attributeRemoved(HttpSessionBindingEvent event)
    {
        attributeCounter--;
        System.out.println("attribute removed");
    }

    public void attributeReplaced(HttpSessionBindingEvent event)
    {
        System.out.println(event.getName() + " replaced");
    }

    public void valueBound(HttpSessionBindingEvent event)
    {
        System.out.println(event.getName() + " bound " + event.getValue());
    }

    public void valueUnbound(HttpSessionBindingEvent event)
    {
        System.out.println(event.getName() + " unbound " + event.getValue());
    }

    // 获取当前在线人数
    public static int getOnlineSession()
    {
        return sessionCounter;
    }

    public static int getOnlineAttribute()
    {
        return attributeCounter;
    }
}
